<template>
  <div class="address-selector-container" style="display: block; width: 100%">
    <!-- 级联选择器 -->
    <el-cascader
        style="width: 700px"
        v-show="!localShowInput"
        ref="cascaderRef"
        v-model="localCodeArr"
        :props="props"
        :options="options"
        @focus="$emit('focus')"
        @change="handleChange"
        @click.native="handleClick"
        @dblclick.native="switchToInput"
        :placeholder="placeholder"
        class="wide-address-selector"
    ></el-cascader>

    <!-- 输入框 -->
    <el-input
        style="width: 700px"
        v-show="localShowInput"
        ref="inputRef"
        v-model="localAddName"
        :placeholder="inputPlaceholder"
        @dblclick.native="switchToCascader"
        @blur="handleBlur"
        class="wide-address-input"
    ></el-input>
  </div>
</template>

<script>
export default {
  props: {
    showInput: Boolean,
    codeArr: Array,
    addName: String,
    options: Array,
    addressType: String,
    props: Object,
    cascaderRef: String,
    inputRef: String,
    placeholder: {
      type: String,
      default: '省/市/县/镇/乡'
    },
    inputPlaceholder: {
      type: String,
      default: '双击切换回选择器'
    }
  },
  data() {
    return {
      localShowInput: this.showInput,
      localCodeArr: this.codeArr,
      localAddName: this.addName
    }
  },
  watch: {
    showInput(val) {
      this.localShowInput = val
    },
    codeArr(val) {
      this.localCodeArr = val
    },
    addName(val) {
      this.localAddName = val
    },
    localCodeArr(val) {
      this.$emit('update:codeArr', val)
    },
    localAddName(val) {
      this.$emit('update:addName', val)
    }
  },
  methods: {
    focusInput() {
      this.switchToInput();
    },

    focusCascader() {
      if (this.$refs.cascaderRef) {
        this.$refs.cascaderRef.focus();
      }
    },

    handleClick() {
      clearTimeout(this.clickTimer)
      this.clickTimer = setTimeout(() => {}, 200)
    },
    switchToInput() {
      this.localShowInput = true;
      this.$nextTick(() => {
        // 安全访问 inputRef
        const inputEl = this.$refs.inputRef?.$el?.querySelector('input') ||
            this.$refs.inputRef?.inputRef;
        if (inputEl?.focus) {
          inputEl.focus();
        } else {
          console.error('输入框引用获取失败', this.$refs);
        }
      });
    },
    switchToCascader() {
      this.localShowInput = false;
    },
    handleBlur() {
      if (!this.localAddName) {
        this.switchToCascader()
      }
    },
    handleChange(val) {
      this.$emit('change', val)
    }
  }
}
</script>